package com.qqtop10.manager.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.qqtop10.manager.service.OrderService;
import com.qqtop10.manager.service.StatisticalService;

@RequestMapping("/manager/statistical/")
@Controller
public class StatisticalController extends BaseController {
	private Logger logger = LoggerFactory.getLogger(StatisticalController.class);
	@Autowired
	@Qualifier("orderService")
	private OrderService orderService;

	@Autowired
	@Qualifier("statisticalService")
	private StatisticalService statisticalService;

	/**
	 * 条件性获取指定商家的统计信息
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("getStatisticalList.do")
	public void getStatisticalList(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/javascript; charset=utf-8");
		Map<String, Object> map = new HashMap<>();
		StringBuffer where = new StringBuffer();
		StringBuffer column = new StringBuffer();
		String uuid = request.getParameter("uuid");
		String groupBy = request.getParameter("groupBy");
		String datetime = request.getParameter("datetime");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		Date date = null;
		try {
			// 查询条件
			where.append(" WHERE tbo.isdeleted = 0");
			where.append(" AND tbo.shop_uuid = '" + uuid + "'");
			where.append(" AND tbo.paytime IS NOT NULL");
			where.append(" AND tbo.payid IS NOT NULL");
			where.append(" AND tbo.trade_no IS NOT NULL");

			// 查询列
			column.append("sum(tbo.s_quantity) sales_quantity,");
			column.append("CONVERT(sum(tbo.actual_price+tbo.walletpay),DECIMAL(10,2)) sales_amount,");
			column.append("CONVERT(sum(tbo.actual_price+tbo.walletpay),DECIMAL(10,2)) profit_amount");
			if (datetime == null || datetime.equals("")) {
				if ("y".equals(groupBy)) {
					where.append(" GROUP BY DATE_FORMAT(tbo.paytime, '%Y')");
					column.append(",DATE_FORMAT(tbo.paytime, '%Y') datetime");
				} else if ("d".equals(groupBy)) {
					where.append(" GROUP BY DATE_FORMAT(tbo.paytime, '%Y-%m-%d')");
					column.append(",DATE_FORMAT(tbo.paytime, '%Y-%m-%d') datetime");
				} else {
					where.append(" GROUP BY DATE_FORMAT(tbo.paytime, '%Y-%m')");
					column.append(",DATE_FORMAT(tbo.paytime, '%Y-%m') datetime");
				}
			} else {
				column.append(", '" + datetime + "' datetime");
				date = sdf.parse(datetime);
				Calendar rightNow = Calendar.getInstance();
				rightNow.setTime(date);
				rightNow.add(Calendar.MONTH, 1);// 日期加1个月
				Date date2 = rightNow.getTime();
				where.append(" AND tbo.paytime > '" + datetime + "'");
				where.append(" AND tbo.paytime < '" + sdf.format(date2) + "'");
			}
			map.put("where", where);
			map.put("column", column);
			map.put("order", "ORDER BY datetime DESC");
			logger.info("获取统计数据成功");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("获取统计数据失败：" + e.getMessage());
		}
		map.put("where", where);
		response.getWriter().print(super.page(map, statisticalService, request));
	}

	/**
	 * 条件性各个商家的统计信息
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("getShopStatisticalList.do")
	public void getShopStatisticalList(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/javascript; charset=utf-8");
		Map<String, Object> map = new HashMap<>();
		StringBuffer from = new StringBuffer();
		StringBuffer where = new StringBuffer();
		StringBuffer column = new StringBuffer();
		try {
			// 查询的表
			from.append(" FROM tb_order tbo ");
			from.append(" INNER JOIN tb_shop tbs ON tbo.shop_uuid = tbs.uuid");
			// 查询条件
			where.append(" WHERE tbo.isdeleted = 0");
			where.append(" AND tbo.paytime IS NOT NULL");
			where.append(" AND tbo.payid IS NOT NULL");
			where.append(" AND tbo.trade_no IS NOT NULL");
			where.append(" GROUP BY tbo.shop_uuid");
			// 查询列
			column.append("tbo.shop_uuid shop_uuid,");
			column.append("tbs.`name` shop_name,");
			column.append("sum(tbo.s_quantity) sales_quantity,");
			column.append("CONVERT(sum(tbo.actual_price+tbo.walletpay),DECIMAL(10,2)) sales_amount,");
			column.append("CONVERT(sum(tbo.actual_price+tbo.walletpay),DECIMAL(10,2)) profit_amount");
			map.put("from", from);
			map.put("where", where);
			map.put("column", column);
			map.put("order", " ORDER BY sales_amount DESC");
			logger.info("获取统计数据成功");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("获取统计数据失败：" + e.getMessage());
		}
		map.put("where", where);
		response.getWriter().print(super.page(map, statisticalService, request));
	}

}
